/*
 * @Author: Shane
 * @Date: 2022-05-31 16:27:15
 * @LastEditTime: 2023-10-29 15:43:31
 * @LastEditors: KaKa
 * @Description: 
 * @FilePath: /kkhttp/lib/kk_inner_dio.dart
 */

import 'dart:io';

import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter/foundation.dart';
import 'package:kk_http/kk_http_cfg.dart';

class KKInnerDio with DioMixin {
  KKInnerDio(
      {BaseOptions? options, KKHttpCfg? cfg, List<Interceptor>? interceptors}) {
    options ??= BaseOptions(
      baseUrl: cfg?.baseUrl ?? "",
      contentType: cfg?.contentType ?? 'application/json',
      connectTimeout: cfg?.connectTimeout,
      sendTimeout: cfg?.sendTimeout,
      receiveTimeout: cfg?.receiveTimeout,
    );
    this.options = options;

    // final cacheOptions = Cache

    if (interceptors != null) {
      this.interceptors.addAll(interceptors);
    }
    if (kDebugMode) {
      this.interceptors.add(LogInterceptor(
            requestHeader: true,
            requestBody: true,
            responseHeader: true,
            responseBody: true,
          ));
    }
    // httpClientAdapter = DefaultHttpClientAdapter();
    if (cfg?.proxy?.isNotEmpty == true) {
      httpClientAdapter = IOHttpClientAdapter(createHttpClient: () {
        final client = HttpClient();
        client.findProxy = (uri) {
          // Proxy all request to localhost:8888.
          // Be aware, the proxy should went through you running device,
          // not the host platform.
          // return 'PROXY localhost:8888';
          return cfg!.proxy!;
        };
        client.badCertificateCallback =
            (X509Certificate cert, String host, int port) => true;
        return client;
      });
    }
  }
}
